package com.hooya.fa.eu.biz.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hooya.fa.eu.api.bo.HsCodeBO;
import com.hooya.fa.eu.api.bo.InvoiceBO;
import com.hooya.fa.eu.api.bo.InvoiceDetailBO;
import com.hooya.fa.eu.api.enums.CompanyEnum;
import com.hooya.fa.eu.biz.dao.entity.MetaProduct;
import com.hooya.fa.eu.biz.dao.entity.ReconfigureInvoice;
import com.hooya.fa.eu.biz.dao.entity.ReconfigureInvoiceDetail;
import com.hooya.fa.eu.biz.dao.mapper.*;
import com.hooya.fa.eu.biz.service.InvoiceService;
import com.hooya.integrated.common.core.util.BeanCopyUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.hooya.fa.eu.api.util.DateExtUtil.getYesterday;

/**
 * @Description 1
 * @Author : Zongz
 * @Copyright Copyright (c) 豪雅集团
 * @Create 2023/12/21
 * @Version 1.0.0
 */
@Slf4j
@Service
@DS("fa_eu")
@AllArgsConstructor
public class InvoiceServiceImpl extends ServiceImpl<InvoiceMapper, ReconfigureInvoice> implements InvoiceService {

    private final InvoiceMapper invoiceMapper;

    private final InvoiceDetailMapper invoiceDetailMapper;

    private final MetaRelationMapper metaRelationMapper;

    private final MetaProductMapper metaProductMapper;

    private final ReconfigureInvoiceMapper reconfigureInvoiceMapper;

    private final ReconfigureInvoiceDetailMapper reconfigureInvoiceDetailMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addB2BInvoice(String startDate, String endDate) {
        long start = System.currentTimeMillis();
        String yesterday = getYesterday(endDate);
        //b2b发票信息
        List<InvoiceBO> invoiceList = invoiceMapper.getB2bInvoiceBoListByDate(startDate, endDate, yesterday);
        //b2b发票明细
        List<InvoiceDetailBO> detailList = invoiceDetailMapper.getB2bDetailBoListByDate(startDate, endDate);
        dealWithDetail(detailList);
        log.info("B2B 发票数据共为：" + invoiceList.size() + "条");
        if (!CollectionUtils.isEmpty(invoiceList)) {
            List<ReconfigureInvoice> res = BeanCopyUtils.turnToVO(invoiceList, ReconfigureInvoice.class);
            reconfigureInvoiceMapper.insertBatchSomeColumn(res);
        }
        log.info("B2B 发票详情数据共为：" + detailList.size() + "条, 共用时为：" + (System.currentTimeMillis() - start) / 1000 + "s");
        if (!CollectionUtils.isEmpty(detailList)) {
            List<ReconfigureInvoiceDetail> res = BeanCopyUtils.turnToVO(detailList, ReconfigureInvoiceDetail.class);
            batchInsertInvoiceDetail(res);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addZyInvoice(String startDate, String endDate) {
        long start = System.currentTimeMillis();
        //转运发票信息
        List<InvoiceBO> invoiceList = invoiceMapper.getZyInvoiceBoListByDate(startDate, endDate);
        //转运发票明细
        List<InvoiceDetailBO> detailList = invoiceDetailMapper.getZyDetailBoListByDate(startDate, endDate);
        dealWithDetail(detailList);
        log.info("转运 发票数据共为：" + invoiceList.size() + "条");
        if (!CollectionUtils.isEmpty(invoiceList)) {
            List<ReconfigureInvoice> res = BeanCopyUtils.turnToVO(invoiceList, ReconfigureInvoice.class);
            reconfigureInvoiceMapper.insertBatchSomeColumn(res);
        }
        log.info("转运 发票详情数据共为：" + detailList.size() + "条, 共用时为：" + (System.currentTimeMillis() - start) / 1000 + "s");
        if (!CollectionUtils.isEmpty(detailList)) {
            List<ReconfigureInvoiceDetail> res = BeanCopyUtils.turnToVO(detailList, ReconfigureInvoiceDetail.class);
            batchInsertInvoiceDetail(res);
        }
    }

    public void dealWithDetail(List<InvoiceDetailBO> detailList) {
        List<HsCodeBO> hsCodeList = metaRelationMapper.getSkuHsCodeList();
        List<MetaProduct> productList = metaProductMapper.selectList(null);
        Map<String, String> belongsResMap = hsCodeList.stream()
                .collect(Collectors.toMap(hc -> hc.getSku() + hc.getBelongs(), HsCodeBO::getHsCode));
        Map<String, HsCodeBO> skuResMap = hsCodeList.stream()
                .collect(Collectors.toMap(HsCodeBO::getSku, i -> i, (k1, k2) -> k1));
        Map<String, MetaProduct> productMap = productList.stream()
                .collect(Collectors.toMap(MetaProduct::getSku, i -> i));
        detailList.forEach(l -> {
            //净重与描述
            MetaProduct product = productMap.get(l.getSku());
            if (Objects.nonNull(product)) {
                l.setDescription(product.getDescription());
                l.setNetwt(product.getNetWt());
            }
            //------------------------hsCode赋值------------------------
            //特殊判断
            if (l.getSku().startsWith("GM21901009") || l.getSku().startsWith("GM21901008")) {
                l.setHsCode("6202401090");
                return;
            }
            if (l.getSku().startsWith("GM11901003") || l.getSku().startsWith("GM11902001")) {
                l.setHsCode("6203339000");
                return;
            }
            if (l.getSku().startsWith("GM11903006")) {
                l.setHsCode("6207991000");
                return;
            }
            if (l.getSku().startsWith("HW68675CDK")) {
                l.setHsCode("9403202000");
                return;
            }
            if (l.getSku().equals("ES10260DE-WH")) {
                l.setHsCode("8179899710");
                return;
            }
            //正常情况：sku+belongs
            String finalHsCode = "";
            if (l.getBelongs().equals(CompanyEnum.COSTWAY_PL.getCompany())
                    || l.getBelongs().equals(CompanyEnum.COSTWAY_FR.getCompany())) {
                String hsCode = belongsResMap.get(l.getSku() + l.getBelongs());
                if (StringUtils.isNotBlank(hsCode)) {
                    finalHsCode = hsCode;
                } else if (l.getBelongs().equals(CompanyEnum.COSTWAY_PL.getCompany())) {
                    finalHsCode = belongsResMap.get(l.getSku() + "globalway");
                }
            }
            if (l.getBelongs().startsWith("fds")) {
                finalHsCode = belongsResMap.get(l.getSku() + "fds");
            }
            if (StringUtils.isNotBlank(finalHsCode)) {
                l.setHsCode(finalHsCode);
            } else {
                //正常情况：sku
                HsCodeBO bo = skuResMap.get(l.getSku());
                if (Objects.nonNull(bo)) {
                    l.setHsCode(bo.getHsCode());
                } else {
                    throw new RuntimeException("sku:" + l.getSku() + ",belongs:" + l.getBelongs() + " 无hsCode");
                }
            }
        });
    }


    public void batchInsertInvoiceDetail(List<ReconfigureInvoiceDetail> res) {
        for (ReconfigureInvoiceDetail detail : res) {
            reconfigureInvoiceDetailMapper.insert(detail);
        }
    }
}
